/**
 * BreadcrumbService, listening the change of location and build the breadcrumb
 * for the application
 * 
 * Use of Class.js
 * 
 * @author david.liu
 */

var BreadcrumbService = Class.extend({

	_breadcrumbs : null,
	_location : null,
	_breadCrumbNames : null,

	/**
	 * Initialize BreadcrumbService
	 */
	init : function($rootScope, $location, breadCrumbNames) {
		this._location = $location;
		this._breadCrumbNames = breadCrumbNames;

		// we want to update breadcrumbs only when a route
		// is actually changed
		// as $location.path() will get updated imediatelly
		// (even if route change fails!)
		$rootScope.$on('$routeChangeSuccess', this._handleRouteChanged
				.bind(this));
	},

	getAll : function() {
		return this._breadcrumbs;
	},

	getFirst : function() {
		return this._breadcrumbs[0] || {};
	},

	_handleRouteChanged : function(event, current) {

		var pathElements = this._location.path().split('/'), result = [], i;
		var breadcrumbPath = function(index) {
			return '/' + (pathElements.slice(0, index + 1)).join('/');
		};

		pathElements.shift();
		for (i = 0; i < pathElements.length; i++) {
			result.push({
				name : this._breadCrumbNames[breadcrumbPath(i)],
				path : breadcrumbPath(i)
			});
		}

		this._breadcrumbs = result;
	}

});

(function() {
	var BreadcrumbServiceProvider = Class.extend({

		instance : null,

		/**
		 * Initialize and configure BreadcrumbService
		 * 
		 * @return BreadcrumbService
		 */
		$get : [
				'$rootScope',
				'$location',
				'BREADCRUMBS.NAMES',
				function($rootScope, $location, breadCrumbNames) {
					if (this.instance == null) {
						this.instance = new BreadcrumbService($rootScope,
								$location, breadCrumbNames);
					}
					return this.instance;
				} ]
	})

	angular.module('services.breadcrumbs', []).provider('breadcrumbs',
			BreadcrumbServiceProvider);
}());